package com.bulkmail.sender.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.bulkmail.sender.DataSession;
import com.bulkmail.sender.XmlOptionsParserReader;
import com.bulkmail.sender.XmlParserReader;

public class OpenActionListener implements ActionListener {

	private MainFrame frame;
	private ZipFile zipFile;

	public OpenActionListener(MainFrame frame) {
		this.frame = frame;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		String mailXml = null;
		String optionXml = null;
		JFrame openFrame = new JFrame();
		JFileChooser fileChooser = new JFileChooser(".");
		FileFilter ff = new FileNameExtensionFilter("zip files", "zip");
		fileChooser.addChoosableFileFilter(ff);
		openFrame.getContentPane().add(fileChooser);

		int result = fileChooser.showOpenDialog(null);

		switch (result) {
		case JFileChooser.APPROVE_OPTION:
			File file = fileChooser.getSelectedFile();
			try {
				zipFile = new ZipFile(file.getAbsolutePath());
				Enumeration<?> enu = zipFile.entries();
				ZipEntry zipEntry = (ZipEntry) enu.nextElement();
				mailXml = getFileFromZip(zipEntry);
				zipEntry = (ZipEntry) enu.nextElement();
				optionXml = getFileFromZip(zipEntry);
				System.out.println(mailXml);
				System.out.println(optionXml);
				zipFile.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			DataSession dataSession = new DataSession();
			XmlParserReader parserReader = new XmlParserReader(mailXml);
			dataSession = parserReader.populateDataSession(dataSession);
			XmlOptionsParserReader parserOptionsReader = new XmlOptionsParserReader(
					optionXml);
			dataSession = parserOptionsReader
					.populateDataSessionOptions(dataSession);

			frame.fromTextField.setText(dataSession.getFrom());

			String temp = "";
			List<String> to = dataSession.getTo();

			for (String string : to) {
				temp += string + ";";
			}

			frame.toTextField.setText(temp);
			frame.subjectTextField.setText(dataSession.getSubject());
			frame.messageArea.setText(dataSession.getMessage());
			frame.attachmentTextField.setText(dataSession.getAttachPath());
			frame.smtpRadioButton.setSelected(dataSession.getSmtp());
			frame.exchangeRadioButton.setSelected(dataSession.getExs());
			frame.serverTextField.setText(dataSession.getServer());
			frame.portTextField.setText(dataSession.getPort());
			frame.userTextField.setText(dataSession.getUsername());
			frame.passwordField.setText(dataSession.getPassword());
			frame.noOfEmailTextField.setText(String.valueOf(dataSession
					.getNrEmails()));
			frame.timeBetweenTextField.setText(String.valueOf(dataSession
					.getSeconds()));
			frame.counterCheckBox.setSelected(dataSession.getAddCounter());
			frame.randomCheckBox.setSelected(dataSession.getAddRandomSubject());
			frame.repaint();
			break;
		case JFileChooser.CANCEL_OPTION:
			System.out.println("Cancel or the close-dialog icon was clicked");
			break;
		case JFileChooser.ERROR_OPTION:
			System.out.println("Error");
			break;
		}

		openFrame.setVisible(true);
		openFrame.pack();

		DataSession dataSession = new DataSession();
		String location = null;
		XmlParserReader parserReader = new XmlParserReader(location);
		dataSession = parserReader.populateDataSession(dataSession);
		XmlOptionsParserReader parserOptionsReader = new XmlOptionsParserReader(
				location);
		dataSession = parserOptionsReader
				.populateDataSessionOptions(dataSession);

		frame.fromTextField.setText(dataSession.getFrom());
		String temp = "";
		for (String s : dataSession.getTo()) {
			temp += s + ";";
		}
		temp = temp.substring(0, temp.length() - 1);
		frame.toTextField.setText(temp);
		frame.subjectTextField.setText(dataSession.getSubject());
		frame.messageArea.setText(dataSession.getMessage());
		frame.attachmentTextField.setText(dataSession.getAttachPath());
		frame.smtpRadioButton.setSelected(dataSession.getSmtp());
		frame.exchangeRadioButton.setSelected(dataSession.getExs());
		frame.serverTextField.setText(dataSession.getServer());
		frame.portTextField.setText(dataSession.getPort());
		frame.userTextField.setText(dataSession.getUsername());
		frame.passwordField.setText(dataSession.getPassword());
		frame.noOfEmailTextField.setText(String.valueOf(dataSession
				.getNrEmails()));
		frame.timeBetweenTextField.setText(String.valueOf(dataSession
				.getSeconds()));
		frame.counterCheckBox.setSelected(dataSession.getAddCounter());
		frame.randomCheckBox.setSelected(dataSession.getAddRandomSubject());

	}

	private String getFileFromZip(ZipEntry zipEntry) {
		String name = zipEntry.getName();
		long size = zipEntry.getSize();
		long compressedSize = zipEntry.getCompressedSize();
		System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n",
				name, size, compressedSize);

		File f = new File(name);
		if (name.endsWith("/")) {
			f.mkdirs();
			// return;
		}

		File parent = f.getParentFile();
		if (parent != null) {
			parent.mkdirs();
		}

		InputStream is = null;
		try {
			is = zipFile.getInputStream(zipEntry);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] bytes = new byte[1024];
		int length;
		try {
			while ((length = is.read(bytes)) >= 0) {
				fos.write(bytes, 0, length);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return f.getAbsolutePath();
	}
}